import db from '../../utils/dbconf';
import makeres from '../../utils/res';
import { IMGAE_BASE } from '../../server.config';
import { TargetDataNoneError } from '../../utils/classModal';
import { unlink } from 'fs';
import { IMGS_PATH } from '../../utils/upload';

export const TABLE_NAME = 'MJ_MATERIAL';

export const materialcrud = {
	getlist: async ({ query }, res) => {
		const { u_id } = res.locals;
		let { page = 1, size = 10, name = '', type = 0 } = query;
		if (!Number(type)) type = ['EXP', 'IS NOT NULL']; // 查询全部
		const { count: total, data: list } = await db
			.table(TABLE_NAME)
			// .field('content', true)
			.where({ name: ['LIKE', `%${name}%`], u_id, type })
			.page(page, size)
			.countSelect();
		return res.send(makeres.success({ total, list }));
	},
	getdetail: async ({ params: { id } }, res) => {
		const { u_id } = res.locals;
		const item = await db.table(TABLE_NAME).where({ id, u_id }).find();
		return res.send(makeres.success(item));
	},
	add: async ({ query: { type }, body: { name }, file: { filename } }, res) => {
		const { u_id } = res.locals;
		if (!name) throw new Error('名称不能为空');
		const content = IMGAE_BASE + '/' + filename;
		const id = await db.table(TABLE_NAME).add({ u_id, type, name, content });
		return res.send(makeres.success({ id, content }));
	},
	change: async ({ params: { id }, body: { name } }, res) => {
		const { u_id } = res.locals;
		if (!name) throw new Error('名称不能为空');
		const ok = await db.table(TABLE_NAME).where({ id, u_id }).update({ name });
		if (!ok) throw new TargetDataNoneError();
		return res.send(makeres.putsuccess());
	},
	delete: async ({ params: { id } }, res) => {
		const { u_id } = res.locals;
		const { content } = await db.table(TABLE_NAME).where({ id, u_id }).find();
		const ok = await db.table(TABLE_NAME).where({ id, u_id }).delete();
		// content:/imgs/file-1682244796788-clvxcyl.jpg
		const filename = content.split('/').pop();
		const path = `${IMGS_PATH}/${filename}`;
		unlink(path, (e) => {
			if (e) console.error(e);
			console.log(`${path} was deleted`);
		});

		if (!ok) throw new TargetDataNoneError();
		return res.send(makeres.deletesuccess());
	},
};
